package com.example.multitenant.multitenant.config

import com.example.multitenant.base.Log
import org.hibernate.MultiTenancyStrategy
import org.hibernate.cfg.AvailableSettings
import org.hibernate.engine.jdbc.connections.spi.AbstractDataSourceBasedMultiTenantConnectionProviderImpl
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.boot.autoconfigure.orm.jpa.HibernatePropertiesCustomizer
import org.springframework.stereotype.Component
import javax.sql.DataSource

/**
 * @author xiang
 * @Date 2022/8/29 10:57
 **/

@Component
class TenantConnectionProvider :
    AbstractDataSourceBasedMultiTenantConnectionProviderImpl(),
    HibernatePropertiesCustomizer {

    companion object {
        private const val TAG = "TenantConnectionProvider"
    }

    @Autowired
    private lateinit var dataSources: DataSources

    override fun selectAnyDataSource(): DataSource {
        Log.i(TAG, "selectAnyDataSource")
        return dataSources.masterDataSource()
    }

    override fun selectDataSource(tenantIdentifier: String?): DataSource {
        Log.i(TAG, "selectDataSource: $tenantIdentifier")
        return dataSources.tenantDataSource(tenantIdentifier)
    }

    override fun customize(hibernateProperties: MutableMap<String, Any>?) {
        hibernateProperties?.put(AvailableSettings.MULTI_TENANT_CONNECTION_PROVIDER, this)
        hibernateProperties?.put(AvailableSettings.MULTI_TENANT, MultiTenancyStrategy.DATABASE)
    }
}